package cn.yy.cloudpay.scan;

import java.util.concurrent.TimeUnit;

import com.newland.mtype.ModuleType;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.light.LightType;
import com.newland.mtype.module.common.scanner.BarcodeScanner;
import com.newland.mtype.module.common.scanner.ScannerListener;

import cn.yy.cloudpay.R;
import cn.yy.cloudpay.activity.BaseActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.CountDownTimer;
import cn.yy.cloudpay.util.ObjectGenerator;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.WebserviceRequset;
import cn.yy.cloudpay.view.LoadingDialog;
import cn.yy.cloudpay.view.TitlebarLayout;
import cn.yy.cloudpay.view.ToastUtil;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

/**
 * 二维码扫描Activity
 * @author yy-01
 *
 */
public class YimaScanActivity extends BaseActivity {

    private TitlebarLayout titlebar;
    private RelativeLayout relativeLayout;
    private Context mContext;
    // 显示支付金额+
    private TextView mTvAmount;
    private EditText et_code;
    private TextView mTvDownTimer;
    private Button searchPay;
    private ImageView mIvPic;
    private BarcodeScanner scanner;
    private int mAmount ;
    private CloudPayApplication mApplication;
    private Integer mPaytype; // 支付类型
    private int mOpType;
    private static Integer SCAN_TIME = 60; // 扫描器运行时长（秒）
    private MyCountDownTimer mc;
    private IndicatorLight light;
    private PopupWindow popupWindow;
    private LoadingDialog mProgress;
    private EditText tv_activity_scancode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yima_scan);
        mContext = this;
        mApplication = (CloudPayApplication) getApplication();
        initView();
    }

    private void initView() {
        mProgress = new LoadingDialog(mContext, "正在加载数据，请稍后");
        mTvAmount = (TextView) findViewById(R.id.tv_activity_scancode_amuont);
        et_code = (EditText) findViewById(R.id.tv_activity_scancode);
        mTvDownTimer = (TextView) findViewById(R.id.tv_activity_scancode_downtime);
        mIvPic = (ImageView) findViewById(R.id.iv_activity_scancode_pic);
        searchPay = (Button)findViewById(R.id.btn_searchPay);
        tv_activity_scancode = (EditText)findViewById(R.id.tv_activity_scancode);
        relativeLayout = (RelativeLayout) findViewById(R.id.titlebar_activity_scancode);
        Intent intent = getIntent();
        mOpType = intent.getIntExtra(Constant.PARAM_OPTYPE, Constant.KEYBOARD_OP_TYPE_PAY);
        mPaytype = intent.getIntExtra(Constant.PARAM_PAYTYPE, Constant.PAY_TYPE_ALIPAY);
        mTvAmount.setText(getAmountText());
        mIvPic.setImageResource(R.drawable.pp_16);
        searchPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchPay(v);
            }
        });
        if("1".equals(mApplication.isMT())) {
            light = (IndicatorLight) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
        }
        titlebar = new TitlebarLayout(mContext, relativeLayout, "请使用二维码/输入翼码付款");
        titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
            @Override
            public void OnRetrunListener(View view) {
                finish();
            }
        });
        mc = new MyCountDownTimer(SCAN_TIME*1000, 1000);
        mc.start();
    }
    private void searchPay(View v){
//        MyAsyncTask task = new MyAsyncTask(); // 创建异步任务
//        task.execute();
        String code = tv_activity_scancode.getText().toString();
        if(StringUtil.isEmpty(code)){
            Toast.makeText(mContext, "请输入翼码", Toast.LENGTH_LONG).show();
            return;
        }
        mc.cancel(); // 定时器结束
        playBeepSoundAndVibrate(); // 播放音频
        stopScanner(); //调用停止扫描器方法
        returnBack(RESULT_OK,code); // 扫描到的授权码
    }

    private void initDialog(){
        View view = LayoutInflater.from(this).inflate(R.layout.activity_yima_dialog, null);
        TextView tv_yima_name = (TextView) view.findViewById(R.id.tv_yima_name);
        TextView tv_card_type = (TextView) view.findViewById(R.id.tv_card_type);
        TextView tv_yima_tprice = (TextView) view.findViewById(R.id.tv_yima_tprice);
        TextView tv_remain_price = (TextView) view.findViewById(R.id.tv_remain_price);
        EditText et_yima_amount = (EditText) view.findViewById(R.id.et_yima_amount);

        popupWindow = new PopupWindow(searchPay, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置窗体的内容
        popupWindow.setContentView(view);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popupWindow.showAsDropDown(searchPay);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10000:
                    Object obj = msg.obj;
                    initDialog();
                    break;
                default:
                    break;
            }
        }
    };

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    /*
     * 初始化扫描器
     */
    private void initModule() {
        scanner = mApplication.getScanner();
        scanner.initScanner(this);
    }

    /*
     * 运行扫描器
     */
    private void runScanner() {
        light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
        scanner.startScan(SCAN_TIME, TimeUnit.SECONDS, new ScannerListener() {
            @Override
            // 异步
            public void onResponse(String[] result) {
                mc.cancel(); // 定时器结束
                playBeepSoundAndVibrate(); // 播放音频
                stopScanner(); //调用停止扫描器方法
                returnBack(RESULT_OK, result[0]); // 扫描到的授权码
            }

            @Override
            public void onFinish() {
                stopScanner();
                light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
            }
        });
    }

    /**
     * 返回上一个页面
     */
    private void returnBack(int resultCode, String scanCode) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(Constant.PARAM_SCANCODE, scanCode);
        YimaScanActivity.this.setResult(resultCode, resultIntent);
        finish();
    }

    /*
     * 展示支付金额
     */
    private Spanned getAmountText() {
        Intent intent = getIntent();
        String amountString = intent.getStringExtra(Constant.PARAM_AMOUNT);
        String summary = intent.getStringExtra(Constant.PARAM_SUMMARY);
        setmAmount(summary);
        String amount = "支付金额：" + amountString + "元";
        return Html.fromHtml(amount);
    }

    private MediaPlayer mediaPlayer;
    // 音量大小
    private static final float BEEP_VOLUME = 10.0f;
    // 震动时长
    private static final long VIBRATE_DURATION = 200L;
    // 是否震动
    private boolean vibrate = true;
    private boolean playBeep = true;

    /*
     * 初始化音频
     */
    private void initBeepSound() {
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        if (mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 使用系统铃声
            // mediaPlayer = MediaPlayer.create(this,
            // RingtoneManager.getActualDefaultRingtoneUri(this,
            // RingtoneManager.TYPE_NOTIFICATION));
            mediaPlayer.setOnCompletionListener(beepListener);
            mediaPlayer.setOnErrorListener(erroListener);
            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                // //使用系统铃声，不再调用prepare（）方法
                mediaPlayer.prepare();
            } catch (Exception e) {
                mediaPlayer = null;
            }
        }
    }

    /*
     * 播放音频
     */
    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
            releaseMedia();
        }
    };

    private final OnErrorListener erroListener = new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            releaseMedia();
            return false;
        }
    };


    public int getmAmount() {
        return mAmount;
    }

    public void setmAmount(String mAmount) {
        this.mAmount = Integer.parseInt(mAmount.trim());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if("1".equals(mApplication.isMT())){
            initModule();
            runScanner();
        }
        initBeepSound();
//		Log.d("ScanCode", "显示界面");
    }

    @Override
    protected void onPause() {
        super.onPause();
        if("1".equals(mApplication.isMT())){
            stopModule();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if("1".equals(mApplication.isMT())) {
            light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
        }
    }

    /**
     * 停止扫描器
     */
    private void stopScanner() {
        scanner.stopScan();
    }

    /*
     * 释放硬件资源
     */
    private void stopModule() {
        if (scanner != null) {
            stopScanner();
//			Log.e("TAG", "调用stopScanner方法");
        }
    }

    /*
     * 释放音频资源
     */
    private void releaseMedia() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
//			Log.e("TAG", "释放音频资源");
        }
    }

    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture
         *      表示以毫秒为单位 倒计时的总数
         *      例如 millisInFuture=1000 表示1秒
         * @param countDownInterval
         *      表示 间隔 多少微秒 调用一次 onTick 方法
         *      例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            returnBack(RESULT_CANCELED, "");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTvDownTimer.setText(String.format("%d", millisUntilFinished / 1000));
        }
    }


    private class MyAsyncTask extends AsyncTask<String, Void, String> {

        private ObjectGenerator generator = new ObjectGenerator(mContext);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgress.show();
            //显示加载动画
        }

        @Override
        protected String doInBackground(String... params) {
            //连接服务器获取数据
            String jsonStr = "";
            String rs = "";
            try {
                jsonStr = generator.getScanPayReqStr(Constant.PAY_TYPE_YIPAY,0, mApplication.getOperator(),params);
                rs = WebserviceRequset.requsetService(jsonStr,mApplication.getServiceAddress());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return rs;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mProgress.dismiss();
            //处理数据，UI提示
            try {
                JSONObject json = new JSONObject(result);
                String resultCode = json.getString("result");
                String returnMsg = json.getString("returnMsg");
                Message message = new Message();
                if("0".equals(resultCode)){
                    message.what = 10000;
                    message.obj = returnMsg;
                    mHandler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(mContext,"查询卡券失败", ToastUtil.WARNING);
            } finally {

            }
        }
    }
}
